import React, { useEffect } from 'react'
import { useRoutes, useLocation, useNavigate } from 'react-router-dom'
import { message } from 'antd'
import AppLoading from '@/pages/components/AppLoading'
import 'antd/dist/antd.less'
import '@/style/global.less'
import router from './router/config'
import { getToken } from '@/utils/session'

function ToLogin () {
  const navigate = useNavigate()
  useEffect(() => {
    navigate('/login')
    message.warning('请登录后访问')
  }, [])
}

function ToPage () {
  const navigate = useNavigate()
  useEffect(() => {
    navigate('/home')
    message.success('您已登录过')
  }, [])
}

function BeforeRouterEnter () {
  const outlet = useRoutes(router)
  const location = useLocation()
  if (location.pathname === '/login' && getToken('token')) {
    return <ToPage />
  }
  if (location.pathname !== '/login' && !getToken('token')) {
    return <ToLogin/>
  }
  return outlet
}

const App = () => {
  return (
    <div className='App'>
        <React.Suspense fallback={<AppLoading/>}>
          <BeforeRouterEnter/>
        </React.Suspense>
    </div>
  )
}
export default App
